package com.coocaa.ops.admin.v1.policygroup.provider.impl;

import com.coocaa.ops.admin.base.AbstractBizImpl;
import com.coocaa.ops.admin.base.exception.AdminBizException;
import com.coocaa.ops.admin.base.language.CommonLanguageProperties;
import com.coocaa.ops.admin.base.service.AbstractSaveServiceImpl;
import com.coocaa.ops.admin.base.validator.InputParamsValidator;
import com.coocaa.ops.admin.v1.audit.AuditUtil;
import com.coocaa.ops.admin.v1.audit.provider.BaseAuditTaskProviderImpl;
import com.coocaa.ops.admin.v1.policygroup.biz.impl.PolicyGroupInfoBizImpl;
import com.coocaa.ops.admin.v1.policygroup.model.DeleteResultModel;
import com.coocaa.ops.admin.v1.policygroup.provider.IPolicyGroupInfoRlsUpdateProvider;
import com.coocaa.ops.admin.v1.policygroup.provider.IPolicyGroupInfoUpdateProvider;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.enums.ResourceTypeEnum;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.base.mybatis.QueryTemplate;
import com.coocaa.ops.common.core.base.util.ResourceStatusValidator;
import com.coocaa.ops.common.core.biz.audit.entity.AuditTaskInfoEntity;
import com.coocaa.ops.common.core.biz.policygroup.constant.PolicyGroupCategoryConstants;
import com.coocaa.ops.common.core.biz.policygroup.entity.PolicyGroupInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author bjh
 * @description 策略组信息原始表-更新provider接口实现
 * @date : 2020-03-12 14:46:04
 */
@Service
public class PolicyGroupInfoUpdateProviderImpl extends AbstractSaveServiceImpl<PolicyGroupInfoEntity> implements IPolicyGroupInfoUpdateProvider {
    @Autowired
    private PolicyGroupInfoBizImpl thisBizImpl;
    @Autowired
    private IPolicyGroupInfoRlsUpdateProvider thisRlsUpdateProvider;
    private static CommonLanguageProperties commonLanguageProperties;

    @Override
    public AbstractBizImpl getAbstractBizImpl() {
        return thisBizImpl;
    }

    @Override
    public void handleSaveRlsInfo(PolicyGroupInfoEntity inputEntity, Integer userId) {
        thisRlsUpdateProvider.saveRls(inputEntity, userId);
    }

    /**
     * 保存
     *
     * @param inputEntity
     * @param userId
     * @return
     */
    @Override
    public PolicyGroupInfoEntity save(PolicyGroupInfoEntity inputEntity, Integer userId) {
        this.saveBaseInfo(inputEntity.getId(), inputEntity, userId);
        return inputEntity;
    }

    /**
     * 删除副本
     *
     * @param id
     * @param version
     * @param userId
     */
    @Override
    public void deleteHistory(Integer id, Integer version, Integer userId) {
        PolicyGroupInfoEntity policyGroupInfoEntity = (PolicyGroupInfoEntity) thisBizImpl.queryById(id);
        if (!BaseAuditTaskProviderImpl.V_1.equals(version) && policyGroupInfoEntity.getCurrentVersion().equals(version)) {
            //如果不是V1版本，而且和当前版本一样
            throw new AdminBizException(commonLanguageProperties.getCopy() + commonLanguageProperties.getSubmitReview() + commonLanguageProperties.getNotDelete());
        }
        if (BaseAuditTaskProviderImpl.V_1.equals(version)) {
            //V1的处理
            thisBizImpl.updateFlag(id, userId, ResourceStatusEnums.OFF_LINE.getStatus());
        }
        //更新副本删除状态
        thisBizImpl.updateHistoryFlag(id, version, userId, ResourceStatusEnums.OFF_LINE.getStatus());
        //更新原始表信息
        PolicyGroupInfoEntity update = new PolicyGroupInfoEntity();
        update.setId(id);
        //置空副本标识
        update.setDuplicateVersion(0);
        update.setModifier(userId);
        thisBizImpl.updateById(update);
        //逻辑删除首页和策略关联关系状态
        thisRlsUpdateProvider.logicDelAllRls(id, version, userId);

    }


    /**
     * 批量删除
     *
     * @param ids
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public DeleteResultModel deleteBatch(Integer[] ids, Integer userId) {
        DeleteResultModel deleteResultModel = new DeleteResultModel();
        String result;
        for (Integer id : ids) {
            PolicyGroupInfoEntity policyGroupInfoEntity = (PolicyGroupInfoEntity) thisBizImpl.queryById(id);
            if (null != policyGroupInfoEntity && PolicyGroupCategoryConstants.isFormal(policyGroupInfoEntity.getPolicyGroupCategory()) && ResourceStatusValidator.isOnline(policyGroupInfoEntity.getStatus())) {
                result = "[ID：" + id + "][" + commonLanguageProperties.getName() + policyGroupInfoEntity.getPolicyGroupName() + "]" + commonLanguageProperties.getAuditSuccess() + commonLanguageProperties.getNotDelete();
                deleteResultModel.setResult(result);
                return deleteResultModel;
            }
            //判断板块是否已提交流程
            AuditTaskInfoEntity taskInfo = AuditUtil.getTaskByIdAndVersionAndType(id, policyGroupInfoEntity.getCurrentVersion(), ResourceTypeEnum.POLICY_GROUP.getValue());
            if (taskInfo != null && taskInfo.getTaskFlag() == 1) {
                result = "[ID：" + id + "][" + commonLanguageProperties.getName() + policyGroupInfoEntity.getPolicyGroupName() + "]" + commonLanguageProperties.getSubmitReview() + commonLanguageProperties.getNotDelete();
                deleteResultModel.setResult(result);
                return deleteResultModel;
            }
            //若存在待审核的副本
            if (InputParamsValidator.isDuplicateExist(policyGroupInfoEntity.getDuplicateVersion())) {
                //判断该副本是否已提交流程
                taskInfo = AuditUtil.getTaskByIdAndVersionAndType(id, policyGroupInfoEntity.getDuplicateVersion(), ResourceTypeEnum.POLICY_GROUP.getValue());
                if (taskInfo != null && taskInfo.getTaskFlag() == 1) {
                    result = "[ID：" + id + "][" + commonLanguageProperties.getName() + policyGroupInfoEntity.getPolicyGroupName() + "]this policy[" + policyGroupInfoEntity.getDuplicateVersion() + "] copies exist in the audit task flow " + commonLanguageProperties.getNotDelete();
                    deleteResultModel.setResult(result);
                    return deleteResultModel;
                }
            }
            //逻辑删除
            this.logicDel(id, userId);
            deleteResultModel.getIds().add(id);
        }
        result = R.SUCCESS;
        deleteResultModel.setResult(result);
        return deleteResultModel;
    }

    @Autowired
    public void setCommonLanguageProperties(CommonLanguageProperties commonLanguageProperties) {
        PolicyGroupInfoUpdateProviderImpl.commonLanguageProperties = commonLanguageProperties;
    }

    @Override
    public void handleCurrentEditAndCopyEdit(Integer autoIncrementId, PolicyGroupInfoEntity inputEntity, Integer userId) {
        this.checkPolicyGroupName(inputEntity);
        super.handleCurrentEditAndCopyEdit(autoIncrementId, inputEntity, userId);
        //删除关联信息
        thisRlsUpdateProvider.deleteAllRls(autoIncrementId, inputEntity.getCurrentVersion());
    }

    @Override
    public void handleNewAdd(PolicyGroupInfoEntity inputEntity, Integer userId) {
        QueryTemplate<PolicyGroupInfoEntity> queryTemplate = QueryTemplate.getEqQueryTemplate("flag", 1);
        queryTemplate.eq("policy_group_name", inputEntity.getPolicyGroupName());
        int count = getAbstractBizImpl().getMapper().selectCount(queryTemplate);
        if (count > 0) {
            throw new AdminBizException("Policy group name already exists!");
        }
        super.handleNewAdd(inputEntity, userId);
    }

    @Override
    public void handleCreateCopy(PolicyGroupInfoEntity inputEntity, Integer userId) {
        super.handleCreateCopy(inputEntity, userId);
        checkPolicyGroupName(inputEntity);
    }
    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    /*************** ===私有方法=== ********************* ===start=== ***************************************/
    /**
     * 逻辑删除
     *
     * @param id
     * @param userId
     */
    private void logicDel(Integer id, Integer userId) {
        thisBizImpl.updateFlag(id, userId, ResourceStatusEnums.OFF_LINE.getStatus());
    }

    private void checkPolicyGroupName(PolicyGroupInfoEntity inputEntity) {
        QueryTemplate<PolicyGroupInfoEntity> queryTemplate = QueryTemplate.getEqQueryTemplate("flag", 1);
        queryTemplate.eq("policy_group_name", inputEntity.getPolicyGroupName())
                .last("limit 2")
        ;
        List<PolicyGroupInfoEntity> list = getAbstractBizImpl().getMapper().selectList(queryTemplate);
        for (PolicyGroupInfoEntity entityDb : list) {
            if (null != inputEntity.getId() && !Objects.equals(inputEntity.getId(), entityDb.getId()) && Objects.equals(entityDb.getPolicyGroupName(), inputEntity.getPolicyGroupName())) {
                throw new AdminBizException("Policy group name already exists");
            }
        }
    }
}
